# -*- coding: utf-8 -*-
import requests
import base64
import json
import logging
from urllib.parse import unquote_plus
import werkzeug.urls
import werkzeug.utils
from werkzeug.exceptions import BadRequest

from odoo import http
from odoo.exceptions import AccessDenied
from odoo.http import request
from odoo.addons.web.controllers.utils import ensure_db, _get_login_redirect_url

_logger = logging.getLogger(__name__)


class FKCSSOController(http.Controller):
    @http.route("/fkc_sso/authorize", type="http", auth="none")
    def wecom_oauth_authorize(self, state, token, **kwargs):
        state = json.loads(base64.standard_b64decode(state))
        dbname = state['db']
        if not http.db_filter([dbname]):
            return BadRequest()
        url = state['redirect'] if state.get('redirect') else '/web'
        sso_url = request.env['ir.config_parameter'].sudo().get_param('fkc.sso.get.user.info.url')
        if not sso_url:
            _logger.info('fkc.sso.get.user.info.url is not set in ir.config_parameter')
        else:
            try:
                # token里有+号，会被识别为空格了
                token = token.replace(' ', '+')
                user_info = requests.post(sso_url, json={'Token': token}).json()
                _logger.info("user info from fkc portal: %s", user_info)
                employee_code = user_info.get('No')
                if employee_code:
                    user = request.env['res.users'].sudo().search([('employee_id.code', '=', employee_code)])
                    if user:
                        pre_uid = request.session.authenticate(dbname, user.login, "fkc_sso->" + user.login)
                        resp = request.redirect(_get_login_redirect_url(pre_uid, url), 303)
                        resp.autocorrect_location_header = False

                        # Since /web is hardcoded, verify user has right to land on it
                        if werkzeug.urls.url_parse(resp.location).path == '/web' and not request.env.user._is_internal():
                            resp.location = '/'
                        return resp
            except AccessDenied:
                # oauth credentials not valid, user could be on a temporary session
                _logger.info(
                    'OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies')
                url = "/web/login?oauth_error=3"
            except Exception as e:
                # signup error
                _logger.exception("fkc_sso authorize error : %s" % str(e))
                url = "/web/login?oauth_error=2"
        redirect = request.redirect(url, 303)
        redirect.autocorrect_location_header = False
        return redirect
